package com.atguigu.tingshu.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;

@Component
public class FeignInterceptor implements RequestInterceptor {

    /**
     * feign调用发生前触发这个方法
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获取原request对象
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        //必须有request情况下才处理
        if(requestAttributes != null){
            HttpServletRequest request = requestAttributes.getRequest();
            //获取原请求对象头中的全部数据
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()){
                //一个个取出来
                String name = headerNames.nextElement();
                String value = request.getHeader(name);
                //存储
                requestTemplate.header(name, value);
            }
        }
    }
}